package cn.iocoder.yudao.module.crossborder.platform.job.amazon;

import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformstore.PlatformStoreDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformstore.PlatformStoreService;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.AmazonBusinessService;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.AmazonSyncProvider;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Amazon数据同步定时任务
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class AmazonSyncJob {

    @Resource
    private AmazonBusinessService amazonBusinessService;

    @Resource
    private AmazonSyncProvider amazonSyncProvider;

    @Resource
    private PlatformStoreService platformStoreService;

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    // Amazon平台ID
    private static final Long AMAZON_PLATFORM_ID = 1L;

    /**
     * Amazon数据同步定时任务
     * 每30分钟执行一次增量同步
     */
    @XxlJob("amazonSyncJob")
    @TenantJob
    public String execute(String param) throws Exception {
        log.info("开始执行Amazon数据同步定时任务: param={}", param);

        try {
            // 解析参数
            Map<String, Object> params = parseJobParams(param);
            String syncType = (String) params.getOrDefault("syncType", "INCREMENTAL");
            Integer hours = (Integer) params.getOrDefault("hours", 1);

            // 1. 获取所有需要同步的Amazon店铺
            List<PlatformStoreDO> amazonStores = getAmazonStores();
            if (amazonStores.isEmpty()) {
                log.info("没有找到需要同步的Amazon店铺");
                return "没有店铺需要同步";
            }

            // 2. 计算同步时间范围
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusHours(hours);

            // 3. 并行执行店铺同步
            Map<String, Object> totalResult = new HashMap<>();
            int successCount = 0;
            int failedCount = 0;

            for (PlatformStoreDO store : amazonStores) {
                try {
                    log.info("开始同步Amazon店铺: storeId={}, storeName={}", store.getId(), store.getName());

                    // 执行增量同步
                    Map<String, Object> storeResult = executeStoreSync(store.getId(), syncType, startTime, endTime);

                    if ((Boolean) storeResult.getOrDefault("success", false)) {
                        successCount++;
                        log.info("Amazon店铺同步成功: storeId={}", store.getId());
                    } else {
                        failedCount++;
                        log.warn("Amazon店铺同步失败: storeId={}, error={}",
                            store.getId(), storeResult.get("message"));
                    }

                    totalResult.put("store_" + store.getId(), storeResult);

                } catch (Exception e) {
                    failedCount++;
                    log.error("Amazon店铺同步异常: storeId={}", store.getId(), e);
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("success", false);
                    errorResult.put("error", e.getMessage());
                    totalResult.put("store_" + store.getId(), errorResult);
                }
            }

            // 4. 汇总结果
            totalResult.put("totalStores", amazonStores.size());
            totalResult.put("successCount", successCount);
            totalResult.put("failedCount", failedCount);
            totalResult.put("syncType", syncType);
            totalResult.put("timeRange", startTime + " ~ " + endTime);

            log.info("Amazon数据同步完成: 总店铺={}, 成功={}, 失败={}",
                amazonStores.size(), successCount, failedCount);

            return String.format("同步完成: 总店铺=%d, 成功=%d, 失败=%d",
                amazonStores.size(), successCount, failedCount);

        } catch (Exception e) {
            log.error("Amazon数据同步失败", e);
            throw e;
        }
    }

    /**
     * Amazon订单同步定时任务
     * 每15分钟执行一次
     */
    @XxlJob("amazonOrderSyncJob")
    @TenantJob
    public String executeOrderSync(String param) throws Exception {
        log.info("开始执行Amazon订单同步定时任务: param={}", param);

        try {
            Map<String, Object> params = parseJobParams(param);
            Integer hours = (Integer) params.getOrDefault("hours", 1);

            List<PlatformStoreDO> amazonStores = getAmazonStores();
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusHours(hours);

            int successCount = 0;
            int failedCount = 0;

            for (PlatformStoreDO store : amazonStores) {
                try {
                    Map<String, Object> result = amazonSyncProvider.syncOrders(store.getId(), startTime, endTime);
                    if ((Boolean) result.getOrDefault("success", false)) {
                        successCount++;
                        log.info("Amazon订单同步成功: storeId={}, syncCount={}",
                            store.getId(), result.get("syncCount"));
                    } else {
                        failedCount++;
                        log.warn("Amazon订单同步失败: storeId={}, error={}",
                            store.getId(), result.get("message"));
                    }
                } catch (Exception e) {
                    failedCount++;
                    log.error("Amazon订单同步异常: storeId={}", store.getId(), e);
                }
            }

            return String.format("订单同步完成: 成功=%d, 失败=%d", successCount, failedCount);

        } catch (Exception e) {
            log.error("Amazon订单同步失败", e);
            throw e;
        }
    }

    /**
     * Amazon库存同步定时任务
     * 每10分钟执行一次
     */
    @XxlJob("amazonInventorySyncJob")
    @TenantJob
    public String executeInventorySync(String param) throws Exception {
        log.info("开始执行Amazon库存同步定时任务: param={}", param);

        try {
            List<PlatformStoreDO> amazonStores = getAmazonStores();
            int successCount = 0;
            int failedCount = 0;

            for (PlatformStoreDO store : amazonStores) {
                try {
                    Map<String, Object> result = amazonSyncProvider.syncInventory(store.getId());
                    if ((Boolean) result.getOrDefault("success", false)) {
                        successCount++;
                        log.info("Amazon库存同步成功: storeId={}, syncCount={}",
                            store.getId(), result.get("syncCount"));
                    } else {
                        failedCount++;
                        log.warn("Amazon库存同步失败: storeId={}, error={}",
                            store.getId(), result.get("message"));
                    }
                } catch (Exception e) {
                    failedCount++;
                    log.error("Amazon库存同步异常: storeId={}", store.getId(), e);
                }
            }

            return String.format("库存同步完成: 成功=%d, 失败=%d", successCount, failedCount);

        } catch (Exception e) {
            log.error("Amazon库存同步失败", e);
            throw e;
        }
    }

    // ==================== 辅助方法 ====================

    /**
     * 获取所有Amazon店铺
     */
    private List<PlatformStoreDO> getAmazonStores() {
        try {
            // 查询platform_store表中platform_id为Amazon的已授权店铺
            return platformStoreService.getAuthorizedStoresByPlatformId(AMAZON_PLATFORM_ID);
        } catch (Exception e) {
            log.error("获取Amazon店铺列表失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 执行店铺同步
     */
    private Map<String, Object> executeStoreSync(Long storeId, String syncType,
                                               LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> result = new HashMap<>();

        try {
            if ("FULL".equals(syncType)) {
                // 全量同步
                result = executeFullSync(storeId);
            } else {
                // 增量同步
                result = executeIncrementalSync(storeId, startTime, endTime);
            }

            return result;
        } catch (Exception e) {
            log.error("执行店铺同步失败: storeId={}", storeId, e);
            result.put("success", false);
            result.put("message", "同步异常: " + e.getMessage());
            return result;
        }
    }

    /**
     * 执行全量同步
     */
    private Map<String, Object> executeFullSync(Long storeId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 全量同步所有数据类型
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(30); // 最近30天

            // 并行执行各种同步
            CompletableFuture<Map<String, Object>> ordersFuture = CompletableFuture.supplyAsync(() ->
                amazonSyncProvider.syncOrders(storeId, startTime, endTime), executorService);

            CompletableFuture<Map<String, Object>> productsFuture = CompletableFuture.supplyAsync(() ->
                amazonSyncProvider.syncProducts(storeId, startTime, endTime), executorService);

            CompletableFuture<Map<String, Object>> inventoryFuture = CompletableFuture.supplyAsync(() ->
                amazonSyncProvider.syncInventory(storeId), executorService);

            // 等待所有任务完成
            CompletableFuture.allOf(ordersFuture, productsFuture, inventoryFuture).join();

            // 收集结果
            Map<String, Object> ordersResult = ordersFuture.get();
            Map<String, Object> productsResult = productsFuture.get();
            Map<String, Object> inventoryResult = inventoryFuture.get();

            result.put("success", true);
            result.put("orders", ordersResult);
            result.put("products", productsResult);
            result.put("inventory", inventoryResult);
            result.put("syncType", "FULL");

        } catch (Exception e) {
            log.error("执行全量同步失败: storeId={}", storeId, e);
            result.put("success", false);
            result.put("message", "全量同步失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 执行增量同步
     */
    private Map<String, Object> executeIncrementalSync(Long storeId, LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 增量同步订单和库存
            Map<String, Object> ordersResult = amazonSyncProvider.syncOrders(storeId, startTime, endTime);
            Map<String, Object> inventoryResult = amazonSyncProvider.syncInventory(storeId);

            boolean ordersSuccess = (Boolean) ordersResult.getOrDefault("success", false);
            boolean inventorySuccess = (Boolean) inventoryResult.getOrDefault("success", false);

            result.put("success", ordersSuccess && inventorySuccess);
            result.put("orders", ordersResult);
            result.put("inventory", inventoryResult);
            result.put("syncType", "INCREMENTAL");

        } catch (Exception e) {
            log.error("执行增量同步失败: storeId={}", storeId, e);
            result.put("success", false);
            result.put("message", "增量同步失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 解析任务参数
     */
    private Map<String, Object> parseJobParams(String param) {
        if (param == null || param.trim().isEmpty()) {
            return new HashMap<>();
        }

        try {
            return objectMapper.readValue(param, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.warn("解析任务参数失败: {}", param, e);
            return new HashMap<>();
        }
    }

}
